import request from '@/utils/request'

// 获取 base url（来自 request 实例）
const baseURL = request.defaults.baseURL || ''

export const getDeepSeekAPI = async (chatting: string, onChunk?: (chunk: string) => void): Promise<void> => {
  const fullUrl = new URL('/deepSeek/chat', baseURL).toString()

  try {
    const response = await fetch(fullUrl, {
      method: 'POST', // 通常 SSE 用 POST 传递参数
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      body: JSON.stringify({ chatting })
    })

    if (!response.ok || !response.body) {
      throw new Error('Network response was not ok')
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value, { stream: true })
      buffer += chunk

      // 解析 SSE 数据
      const lines = buffer.split('\n')
      buffer = ''
      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.slice(5).trim()
          if (data) {
            if (onChunk) {
              onChunk(data)
            }
          }
        } else {
          // 非完整数据行，存回 buffer
          buffer += line + '\n'
        }
      }
    }
  } catch (error) {
    console.error('Error fetching SSE data:', error)
    throw error
  }
}